package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.common.util.Utility;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.AtributosService;
import co.gov.medellin.ssti.sub.model.service.BeneficioService;
import co.gov.medellin.ssti.sub.model.service.EmpresaService;
import co.gov.medellin.ssti.sub.model.service.ProgramaService;
import co.gov.medellin.ssti.sub.model.service.SubprogramaService;
import co.gov.medellin.ssti.sub.model.vo.EmpresaVO;
import co.gov.medellin.ssti.sub.model.vo.ProgramaVO;
import co.gov.medellin.ssti.sub.model.vo.SubprogramaVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;
import co.gov.medellin.ssti.sub.web.form.OtorgarBeneficiosEmpresaForm;

@Component
public class OtorgarBeneficiosEmpresaAction extends Action {
	@Autowired
	AtributosService atributosServiceImpl;
	@Autowired
	EmpresaService empresaServiceImpl;
	@Autowired
	BeneficioService beneficioServiceImpl;
	@Autowired
	ProgramaService programaServiceImpl;
	@Autowired
	SubprogramaService subprogramaServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		UserVO user = (UserVO) request.getSession().getAttribute("userInfo");
		ActionMessages messages = new ActionMessages();
		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);
		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
				return null;
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
				return null;
			} else {
				return mapping.getInputForward();
			}

		}

		OtorgarBeneficiosEmpresaForm formBean = (OtorgarBeneficiosEmpresaForm) form;

		String strCodigoEmpresa = request.getParameter("codigoEmpresa");
		if (strCodigoEmpresa != null && strCodigoEmpresa.length() > 0) {
			EmpresaVO empresaVO = empresaServiceImpl.findEmpresaByCodigo(Long
					.valueOf(strCodigoEmpresa));
			if (empresaVO != null) {
				formBean.setEmpresaVO(empresaVO);
			}
		}

		String strCodigoPrograma = formBean.getCodigoPrograma();
		String strCodigoSubprograma = formBean.getCodigoSubprograma();

		HttpSession session = request.getSession();

		Collection<ProgramaVO> programas = null;
		Collection<SubprogramaVO> subprogramas = null;

		ProgramaVO objProgramaVO = new ProgramaVO();
		SubprogramaVO objSubProgramaVO = new SubprogramaVO();

		formBean.getProgramas().clear();
		try {

			programas = programaServiceImpl.findProgramaByCriteriaOB(
					objProgramaVO, user.getCode(), user.getUserGroupName(),
					user.getCodeArea());

			// TODO: programas para empresa dependiendo de criteria
			// programas = empresaServiceImpl.findProgramasParaEmpresa();
		} catch (DAOException e) {
			SUBException.logDebugError("", e);
		}
		session.removeAttribute("msg");
		if (programas.size() > 0) {
			formBean.setProgramas(programas);
		} else {
			session.setAttribute("msg",
					"No se encontraron programas vigentes a la fecha..");
		}
		if (formBean.getSubprogramas() != null) {
			formBean.getSubprogramas().clear();
		}

		if (strCodigoSubprograma != null) {
			if (!strCodigoPrograma.equals("")) {
				try {
					objSubProgramaVO.setCodePrograma(Long
							.valueOf(strCodigoPrograma));

					subprogramas = subprogramaServiceImpl
							.findSubprogramaByCriteria(objSubProgramaVO,
									user.getCode(), user.getUserGroupName(),
									user.getCodeArea());

					// TODO: criteria subprogramas.
					// subprogramas = empresaServiceImpl
					// .findSubprogramasParaEmpresa(Long
					// .valueOf(strCodigoPrograma));
				} catch (Exception e) {
					SUBException.logDebugError("", e);
				}
				session.removeAttribute("msg");
				if (subprogramas.size() > 0) {
					formBean.setSubprogramas(subprogramas);
				} else {
					session.setAttribute("msg",
							"No se encontraron subprogramas asociados a este programa que esten vigentes..");
				}
			} else {
				session.setAttribute("msg", "");
			}
		}

		// Hace click en el boton Continuar.
		if (formBean.getOperacion().equals(Utility.OP_GUARDAR)) {
			if (strCodigoSubprograma == null || strCodigoSubprograma.equals("")) {
				// TODO: no continuar
			} else {
				boolean exists = beneficioServiceImpl.isEmpresaBeneficiario(
						Long.valueOf(formBean.getEmpresaVO().getCodigo()),
						Long.valueOf(formBean.getCodigoSubprograma()));

				if (!exists) {
					request.setAttribute("codigoEmpresa", strCodigoEmpresa);
					ActionForward actionRedirect = new ActionForward(mapping
							.findForward("ir").getName(), mapping.findForward(
							"ir").getPath()
							+ "?codigoEmpresa="
							+ strCodigoEmpresa
							+ "&codigoSubprograma=" + strCodigoSubprograma,
							true);
					return actionRedirect;
				} else {
					session.setAttribute(
							"msgdar",
							"La empresa ya tiene el beneficio. Si el icono de renovar esta presente por favor hacer clic");
					request.setAttribute("codigoEmpresa", strCodigoEmpresa);
					ActionForward actionRedirect = new ActionForward(mapping
							.findForward("fail").getName(), mapping
							.findForward("fail").getPath()
							+ "?codigoEmpresa="
							+ strCodigoEmpresa, true);
					return actionRedirect;
				}
			}

		}

		return mapping.findForward("success");
	}
}
